from django.http import JsonResponse
from django.views import View
from rest_framework_simplejwt.tokens import RefreshToken
from user.models import SysUser
from rest_framework.response import Response
import json
from rest_framework.views import APIView
from rest_framework import status
#from .serializers import UserProfileSerializer
#业务登录逻辑
class LoginView(View):
    def post(self, request):
        # 解析JSON请求体
        data = json.loads(request.body)
        username = data.get("username")
        password = data.get("password")
        # username = request.POST.get("username")
        # password = request.POST.get("password")

        print(username, password)
        try:
            # 验证用户名和密码是否为空
            if not username or not password:
                return JsonResponse({
                    'code': 400,
                    'info': '用户名和密码不能为空！',
                    'data': {'token': None,"tokenHeader": "Bearer"}
                })
            #查询数据库是否有匹配的用户
            user = SysUser.objects.get(username=username, password=password)
            if user:
                token = RefreshToken.for_user(user).access_token
                print(user, token)
                return JsonResponse({
                    'code': 200,
                    'info': '登录成功！',
                    'data': {'token': str(token),"tokenHeader": "Bearer "}  # 转换为字符串
                })
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': 401,  # 更合适的HTTP状态码
                'info': '用户名或者密码错误！',
                'data': {'token': None,"tokenHeader": "Bearer"}
            })
        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'info': '请求格式错误，请发送JSON格式数据！',
                'data': {'token': None,"tokenHeader": "Bearer"}
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'info': f'服务器错误：{str(e)}',
                'data': {'token': None,"tokenHeader": "Bearer"}
            })


#获取菜单样例文档：
class menuView(View):
    
    def get(self,request):
        # token = RefreshToken.for_user(request.user)
        token = request.META.get('HTTP_AUTHORIZATION')

        print('下面需要用严格模式对token进行严格模式验证  和服务器的token不一致 返回401')
        # # 解析JSON请求体
        # data = json.loads(request.body)
        # username = data.get("username")
        # password = data.get("password")

        # user = SysUser.objects.get(username=username, password=password)
        # token = RefreshToken.for_user(user).access_token
        # print(token)
        # if user_token != token :
        #     return  JsonResponse({
        #         'code': 401,
        #         'info': 'token认证失败！',
        #         'data': {"id":999,
        #                  "title":"",
        #                  "icon":"",
        #                  "roles": [""],
        #                  "path":"",  
        #                  "menus":[]
        #                 }
        #         })
            
        if token != None and token != '':
            # menuList_obj=SysUser.objects.all()
            # print(menuList_obj,type(menuList_obj))
            # menuList_dict=menuList_obj.values() # 转存字典
            

            return  JsonResponse({
                'code': 200,
                'info': '操作信息成功',
                'data': {"id":1,"title":"系统管理",
                         "icon":"el-icon-setting",
                         "roles": ["超级管理员"],
                         "path":"/admin/info",  
                         "menus":[{"id":1,"title":"权限管理","icon":"权限管理","path":"/system/permission","parentId":0,"level":"0","sort":0,"hidden":0,"name":"ums"}, #hidderm显示隐藏
                                  {"id":2,"title":"用户管理","icon":"用户管理","path":"/system/user","parentId":1,"level":"1","sort":0,"hidden":0,"name":"user"},
                                  {"id":3,"title":"角色管理","icon":"role_icon","path":"/system/role","parentId":1,"level":"1","sort":0,"hidden":0,"name":"role"},
                                  {"id":4,"title":"菜单管理","icon":"menu-management","path":"/system/menu","parentId":1,"level":"1","sort":0,"hidden":0,"name":"menu"},
                                  {"id":5,"title":"资产管理","icon":"asset-monitor_surface","path":"/system/menu","parentId":0,"level":"0","sort":0,"hidden":0,"name":"asset"},
                                  {"id":6,"title":"主机管理","icon":"hosting","path":"/system/menu","parentId":5,"level":"1","sort":0,"hidden":0,"name":"host"},
                                  {"id":7,"title":"API管理","icon":"app-api","path":"/system/menu","parentId":5,"level":"1","sort":0,"hidden":0,"name":"appapi"},
                                  {"id":10,"title":"组件管理","icon":"middleware","path":"/system/menu","parentId":5,"level":"1","sort":0,"hidden":0,"name":"middleware"},
                                  {"id":11,"title":"脚本管理","icon":"脚本","path":"/system/menu","parentId":5,"level":"19","sort":0,"hidden":0,"name":"script"},
                                  {"id":20,"title":"数据管理","icon":"数据","path":"/system/menu","parentId":0,"level":"0","sort":0,"hidden":0,"name":"datacenter"},
                                  {"id":30,"title":"工具中心","icon":"工具中心","path":"/system/menu","parentId":0,"level":"0","sort":0,"hidden":0,"name":"tools"},
                                  {"id":40,"title":"任务管理","icon":"任务-蓝","path":"/system/menu","parentId":0,"level":"0","sort":0,"hidden":0,"name":"tasks"},
                                  {"id":8,"title":"添加用户","icon":"任务-蓝","path":"/system/menu","parentId":3,"level":"1","sort":0,"hidden":0,"name":"addUser"},
                                  {"id":9,"title":"分配角色","icon":"任务-蓝","path":"/system/menu","parentId":3,"level":"1","sort":0,"hidden":0,"name":"allocRole"},
                                  {"id":12,"title":"分配角色","icon":"任务-蓝","path":"/system/menu","parentId":3,"level":"1","sort":0,"hidden":0,"name":"editUser"},


                                ], # parentId=0表示一级菜单 后面parentId等于parentId为o的id就是隶属于那个菜单。，
                         "username": "admin",
                         }
            })
        else:
            return JsonResponse({
                'code': 401,
                'info': '用户认证失败,重新登录！',
                'data': 'null'
            })



#1 获取用户列表：
class userListView(View):
    def get(self,request):  #根据分页进行获取用户数据
        #校验携带token  这里先不处理 只是实现前段功能  如果这里的数据必须要多 需要去前段对数据格式进行约束
        token = request.META.get('HTTP_AUTHORIZATION')
        #请求参数：
        pairams = request.GET
        print(pairams.get('keyword'),pairams.get('pageNum'),pairams.get('pageSize'))
        #这里因为是没有用到数据库 只是用的是模拟数据库  数据库的话到用数据模型
        if token != None and token != '':
            if pairams.get('keyword') == 'admin':
                return  JsonResponse({
                    'code': 200,
                    'info': '获取用户列表成功',
                    'data': {
                            "pageNum": 1,
                            "pageSize": 10,
                            "totalPage": 10,
                            "total": 56,
                            "list": [{
                                    "id": 1,
                                    "username": "admin",
                                    "password": "************",
                                    "icon": "null",
                                    "email": "ceshi@qq.com",
                                    "nickName": "sssss",
                                    "status": 1,
                                    "note": "2sdsd",
                                    "role": "string",
                                    "createTime": "2021-05-05 07:05:05",
                                    "loginTime": "2021-05-05 07:05:05",
                                    "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                                    }
                                ],
                            }
                })

            else:
                return  JsonResponse({
                    'code': 200,
                    'info': '获取用户列表成功',
                    'data': {
                            "pageNum": 1,
                            "pageSize": 10,
                            "totalPage": 10,
                            "total": 66,
                            "list": [{
                                    "id": 1,
                                    "username": "admin",
                                    "password": "************",
                                    "icon": "null",
                                    "email": "ceshi@qq.com",
                                    "nickName": "sssss",
                                    "status": 1,
                                    "note": "2sdsd",
                                    "role": "string",
                                    "createTime": "2021-05-05 07:05:05",
                                    "loginTime": "2021-05-05 07:05:05",
                                    "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                                    },
                                    {
                                    "id": 2,
                                    "username": "zhaolei",
                                    "password": "************",
                                    "icon": "null",
                                    "email": "ceshssi@qq.com",
                                    "nickName": "zl",
                                    "status": 0,
                                    "note": "2sdsd",
                                    "role": "string",
                                    "createTime": "2021-05-05 07:05:05",
                                    "loginTime": "2021-05-05 07:05:05",
                                    "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                                    },
                                    
                                    {
                                    "id": 3,
                                    "username": "zhaolei",
                                    "password": "************",
                                    "icon": "null",
                                    "email": "ceshssi@qq.com",
                                    "nickName": "zl",
                                    "status": 1,
                                    "note": "2sdsd",
                                    "role": "string",
                                    "createTime": "2021-05-05 07:05:05",
                                    "loginTime": "2021-05-05 07:05:05",
                                    "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                                    },
                                    
                                ],
                            }
                })
        else:
            return JsonResponse({
                'code': 401,
                'info': '用户认证失败,重新登录！',
                'data': 'null'
            })
#2 更改用户状态：status的1和0的变更：
def changeStatus(request,user_id): 
    print(request.body,user_id)
    #返回的json数据  data是从数据库获取的  修改完然后在查询 在返回的时候再返回
    return JsonResponse({
        'code': 200,
        'info': '修改用户状态成功',
        'data': [{
                "id": 1,
                "username": "zhaolei",
                "password": "************",
                "icon": "null",
                "email": "ceshssi@qq.com",
                "nickName": "zl",
                "status": 1,
                "note": "2sdsd",
                "role": "string",
                "createTime": "2021-05-05 07:05:05",
                "loginTime": "2021-05-05 07:05:05",
                "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                }]
    })


def getUserById(request,user_id):
    print(request.body,user_id)
    return JsonResponse({
        'code': 200,
        'info': '获取用户成功',
        'data': {
                "id": 3,
                "username": "zhaolei",
                "password": "************",
                "icon": "null",
                "email": "ceshssi@qq.com",
                "nickName": "zl",
                "status": 1,
                "note": "2sdsd",
                "role": "string",
                "createTime": "2021-05-05 07:05:05",
                "loginTime": "2021-05-05 07:05:05",
                "avta": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                }
    })


#更新用户信息的接口
class UpdateUserView(APIView):
    """
    更新用户信息的接口
    """
    print('这里是更新用户信息的接口')
    # def put(self, request, *args, **kwargs):
    #     """
    #     处理 PUT 请求来更新用户信息
    #     """
    #     # 1. 从前端传递的参数中获取 id
    #     user_id = request.data.get('id')

    #     # 2. 检查 id 是否存在
    #     if not user_id:
    #         return Response(
    #             data={'code': 400, 'info': '缺少用户ID'},
    #             status=status.HTTP_400_BAD_REQUEST
    #         )

    #     try:
    #         # 3. 根据 id 获取用户实例
    #         user_instance = UserProfile.objects.get(id=user_id)
    #     except UserProfile.DoesNotExist:
    #         # 4. 如果用户不存在，返回错误信息
    #         return Response(
    #             data={'code': 404, 'info': '用户不存在'},
    #             status=status.HTTP_404_NOT_FOUND
    #         )

    #     # 5. 使用序列化器进行数据验证和更新
    #     #    instance: 要更新的模型实例
    #     #    data: 前端传来的新数据
    #     #    partial=True: 允许部分更新，即前端可以只传 name 或只传 age
    #     serializer = UserProfileSerializer(instance=user_instance, data=request.data, partial=True)

    #     # 6. 检查数据是否有效
    #     if serializer.is_valid():
    #         # 7. 如果有效，保存更新
    #         serializer.save()
    #         # 8. 返回成功信息
    #         return Response(
    #             data={'code': 200, 'info': '用户信息更新成功'},
    #             status=status.HTTP_200_OK
    #         )
    #     else:
    #         # 9. 如果数据无效，返回验证错误
    #         return Response(
    #             data={'code': 422, 'info': '数据验证失败', 'errors': serializer.errors},
    #             status=status.HTTP_422_UNPROCESSABLE_ENTITY
    #         )



#获取用户角色的接口
# class getRoleList(APIView):
class getRoleList(View):
    """
    获取用户角色的接口
    """
    print('这里是获取用户角色的接口')
    def get(self, request):
        return JsonResponse({
            'code': 200,
            'info': '获取用户角色成功',
            'data': {      "pageNum": 1,
                            "pageSize": 10,
                            "totalPage": 10,
                            "total": 66,
                            "list": 
                            [{
                                "id": 1,
                                "roleName": "超级管理员",
                                "description": "超级管理员",
                                "createTime": "2021-05-05 07:05:05",
                                # "updateTime": "2021-05-05 07:05:05",
                                "adminCount": 1,
                                "status": 1,
                                "resourceIds": "sss",
                                "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
                            },
                            {
                                "id": 2,
                                "roleName": "开发者",
                                "description": "开发者",
                                "createTime": "2021-05-05 07:05:05",
                                # "updateTime": "2021-05-05 07:05:05",
                                "adminCount": 3,
                                "status": 1,
                                "resourceIds": "sss",
                                "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
                            },
                            {
                                "id": 3,
                                "roleName": "运维管理员",
                                "description": "运维管理员",
                                "createTime": "2021-05-05 07:05:05",
                                # "updateTime": "2021-05-05 07:05:05",
                                "adminCount": 5,
                                "status": 0,
                                "resourceIds": "sss",
                                "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
                            },
                            {
                                "id": 4,
                                "roleName": "部门领导",
                                "description": "部门领导",
                                "createTime": "2021-05-05 07:05:05",
                                # "updateTime": "2021-05-05 07:05:05",
                                "adminCount": 3,
                                "status": 0,
                                "resourceIds": "sss",
                                "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
                            }],
            }
        })

#获取指定用户角色的接口
def getRoleUserIdList(request, user_id):
    print(request.body,user_id)
    return JsonResponse({
        'code': 200,
        'info': '获取用户角色成功',
        'data': [
            {
                "id": 1,
                "name": "超级管理员",
                "description": "超级管理员",
                "createTime": "2021-05-05 07:05:05",
                # "updateTime": "2021-05-05 07:05:05",
                "adminCount": 1,
                "status": 1,
                "resourceIds": "sss",
                "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
            },
            {
                    "id": 4,
                    "name": "部门领导",
                    "description": "部门领导",
                    "createTime": "2021-05-05 07:05:05",
                    # "updateTime": "2021-05-05 07:05:05",
                    "adminCount": 1,
                    "status": 1,
                    "resourceIds": "sss",
                    "menuIds": "1,2,3,4,5,6,7,8,9,10,11,12",
                },
        ]
    })






class TestView(View):

    def get(self,request):
        # token = RefreshToken.for_user(request.user)
        token = request.META.get('HTTP_AUTHORIZATION')
        print(token)
        if token != None and token != '':
            userList_obj=SysUser.objects.all()
            print(userList_obj,type(userList_obj))
            userList_dict=userList_obj.values() # 转存字典
            print(userList_dict, type(userList_dict))
            userList=list(userList_dict) # 把外层的容器转存List
            print(userList, type(userList))
            return JsonResponse({'code':200,'info':'测试！','data':userList})
        else:
            return JsonResponse({'code':401,'info':'用户认证失败！','data':'null'})

class JwtTestView(View):
    def get(self, request):
        #这里是直接写死了用户名和密码，获取token的需要这里进行修改
        user = SysUser.objects.get(username='admin', password='admin')
        refresh = RefreshToken.for_user(user)
        return JsonResponse({
            'code': 200,
            'token': str(refresh.access_token),
            'refresh_token': str(refresh),
        })
